package com.edu.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.orderservice.domain.TOrder;
import com.edu.orderservice.domain.TPayLog;
import com.edu.orderservice.mapper.TPayLogMapper;
import com.edu.orderservice.service.TOrderService;
import com.edu.orderservice.service.TPayLogService;
import com.edu.orderservice.utils.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author ljw
 * @since 2022-09-26
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderService orderService;

    @Override
    public Map createNative(String orderNo) {

        try {
        //1.根据订单号查询订单信息
            QueryWrapper<TOrder> wrapper=new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            TOrder order = orderService.getOne(wrapper);

        //2.使用map设置二维码需要参数
            Map<String,String> map=new HashMap<>();
            map.put("appid","wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", order.getCourseTitle());    //课程标题
            map.put("out_trade_no", orderNo); //订单号
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            map.put("trade_type", "NATIVE");//支付类型


        //3.发送httpclient参数 ,传递参数xml格式 ,微信支付提供固定的地址
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //发送
            client.post();

        //4.得到发送请求接口返回数据
            String content = client.getContent();//xml格式
            //把xml格式转成map
            Map<String,String> resultmap=WXPayUtil.xmlToMap(content);
            //封装数据
            Map mapresponse = new HashMap<>();
            mapresponse.put("out_trade_no", orderNo);
            mapresponse.put("course_id", order.getCourseId());
            mapresponse.put("total_fee", order.getTotalFee());
            mapresponse.put("result_code", resultmap.get("result_code"));
            mapresponse.put("code_url", resultmap.get("code_url"));

            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return mapresponse;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装请求参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            //https
            client.setHttps(true);
            //发送请求
            client.post();
            //3、返回第三方的数据 返回响应数据
            String xml = client.getContent();
            //6、转成Map
            //7、返回
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //对订单的更新和支付记录的添加
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //获取订单id
        String orderNo = map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);
        //如果订单支付状态是1代表已经支付过了
        if(order.getStatus().intValue() == 1) return;
        //没有就设置成1  表示支付了
        order.setStatus(1);
        //修改
        orderService.updateById(order);

        //记录支付日志
        TPayLog payLog=new TPayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);//插入到支付日志表
    }
}
